package com.hsl.housaileibot001.service;

import com.hsl.housaileibot001.model.dto.MockExamGenerationMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

/**
 * Kafka Producer 服务
 */
@Service
public class MockExamGenerationProducerService {

    private static final Logger logger = LoggerFactory.getLogger(MockExamGenerationProducerService.class);

    @Value("${kafka.topic.mock-exam-generation:mock-exam-generation}")
    private String topicName;

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    /**
     * 发送单个消息
     *
     * @param message 消息
     */
    public void sendMessage(MockExamGenerationMessage message) {
        try {
            CompletableFuture<SendResult<String, Object>> future = kafkaTemplate.send(
                    topicName,
                    UUID.randomUUID().toString(),
                    message
            );
            future.whenComplete((result, ex) -> {
                if (ex == null) {
                    logger.info("消息发送成功: taskId={}, interviewQuestionId={}, offset={}",
                            message.getTaskId(), message.getInterviewQuestionId(), result.getRecordMetadata().offset());
                } else {
                    logger.error("消息发送失败: taskId={}, interviewQuestionId={}", 
                            message.getTaskId(), message.getInterviewQuestionId(), ex);
                }
            });
        } catch (Exception e) {
            logger.error("发送消息异常: taskId={}, interviewQuestionId={}", 
                    message.getTaskId(), message.getInterviewQuestionId(), e);
            throw e;
        }
    }

    /**
     * 批量发送消息
     *
     * @param messages 消息列表
     */
    public void sendBatchMessages(List<MockExamGenerationMessage> messages) {
        for (MockExamGenerationMessage message : messages) {
            sendMessage(message);
        }
        logger.info("批量发送消息完成，共 {} 条", messages.size());
    }
}

